<template>
  <div class="regression-analysis-chart">
    <div class="loading" v-if="isLoading">
      <span class="loading-text">回归分析图加载中...</span>
    </div>
    <div class="error" v-if="isError">
      <span class="error-text">图表加载失败，请刷新重试</span>
    </div>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import echarts from '@/utils/echarts-config'
import ecStat from 'echarts-stat'
// 导入 JSON 数据文件
import gdpData from '@/data/gdpRegressionData.json'

echarts.registerTransform(ecStat.transform.regression)

const chartContainer = ref(null)
let myChart = ref(null)
const isLoading = ref(true)
const isError = ref(false)

// 处理 JSON 数据：转换为 ECharts 所需的 [年份差, GDP] 格式（年份差=当前年-1980）
const formatSourceData = () => {
  return gdpData.sourceData.map(item => [
    item.year - 1980, // 保持原逻辑的 x 轴数值（1981→1，1982→2...）
    item.gdp
  ])
}

// 动态计算图表配置（根据容器尺寸自适应）
const getAdaptiveOption = (containerWidth, containerHeight) => {
  const scale = Math.min(containerWidth / 800, containerHeight / 500) || 1;
  const titleFontSize = Math.max(12, 14 * scale);
  const subTitleFontSize = Math.max(10, 11 * scale);
  const axisLabelFontSize = Math.max(8, 9 * scale);
  const symbolSize = Math.max(4, 6 * scale);
  const lineWidth = Math.max(1, 1.5 * scale);
  const labelFontSize = Math.max(8, 10 * scale);

  return {
    grid: {
      containLabel: true,
      left: '8%',
      right: '5%',
      top: '18%',
      bottom: '12%',
      backgroundColor: 'transparent'
    },
    dataset: [
      {
        source: formatSourceData() // 使用处理后的 JSON 数据
      },
      {
        transform: {
          type: 'ecStat:regression',
          config: { 
            method: gdpData.chartConfig.regressionMethod, // 从 JSON 读取回归方法
            dimensions: [0, 1] 
          }
        }
      }
    ],
    title: {
      text: gdpData.chartConfig.title, // 从 JSON 读取标题
      subtext: gdpData.chartConfig.subTitle, // 从 JSON 读取副标题
      left: 'center',
      top: 10,
      textStyle: { 
        color: '#00eaff', 
        fontSize: titleFontSize,
        textShadow: '0 0 6px rgba(0,255,255,0.5)' 
      },
      subtextStyle: { 
        color: '#87cefa', 
        fontSize: subTitleFontSize 
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      backgroundColor: 'rgba(0,10,30,0.8)',
      borderColor: '#00eaff',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: (params) => {
        const param = params[0];
        const year = 1980 + param.value[0];
        return `${year}年\nGDP: ${param.value[1].toFixed(2)} 万亿元`;
      }
    },
    xAxis: {
      name: gdpData.chartConfig.xAxisName, // 从 JSON 读取 x 轴名称
      nameLocation: 'middle',
      nameGap: 25,
      nameTextStyle: { 
        color: '#00eaff', 
        fontSize: axisLabelFontSize,
        padding: [5, 0, 0, 0]
      },
      axisLine: { lineStyle: { color: 'rgba(0,255,255,0.5)' }},
      axisTick: { lineStyle: { color: 'rgba(0,255,255,0.3)' }},
      splitLine: { 
        show: true,
        lineStyle: { type: 'dashed', color: 'rgba(0,255,255,0.2)' } 
      },
      axisLabel: { 
        color: '#00eaff', 
        fontSize: axisLabelFontSize,
        rotate: 30,
        margin: 8
      },
      min: 0,
      max: 19
    },
    yAxis: {
      name: gdpData.chartConfig.yAxisName, // 从 JSON 读取 y 轴名称
      nameLocation: 'end',
      nameGap: 15,
      nameTextStyle: { 
        color: '#00eaff', 
        fontSize: axisLabelFontSize 
      },
      axisLine: { lineStyle: { color: 'rgba(0,255,255,0.5)' }},
      axisTick: { lineStyle: { color: 'rgba(0,255,255,0.3)' }},
      splitLine: { 
        show: true,
        lineStyle: { type: 'dashed', color: 'rgba(0,255,255,0.2)' } 
      },
      axisLabel: { 
        color: '#00eaff', 
        fontSize: axisLabelFontSize,
        margin: 8
      },
      min: -2000,
      max: 90000
    },
    series: [
      {
        name: '实际GDP数据',
        type: 'scatter',
        datasetIndex: 0,
        symbolSize: symbolSize,
        itemStyle: { 
          color: '#00eaff', 
          shadowBlur: 3, 
          shadowColor: 'rgba(0,255,255,0.5)' 
        },
        emphasis: {
          scale: true,
          scaleSize: symbolSize * 1.5
        }
      },
      {
        name: '回归趋势线',
        type: 'line',
        smooth: true,
        datasetIndex: 1,
        symbolSize: 0.1,
        lineStyle: { 
          color: '#00ff9f', 
          width: lineWidth, 
          shadowBlur: 2, 
          shadowColor: 'rgba(0,255,159,0.5)' 
        },
        label: {
          show: true,
          fontSize: labelFontSize,
          color: '#00ff9f',
          formatter: (params) => params.dataIndex === 0 ? (params.value[2] || '回归趋势') : '',
          position: 'top'
        },
        encode: { label: 2, tooltip: 1 }
      }
    ]
  };
};

const initChart = () => {
  if (!chartContainer.value) return;

  const { clientWidth: containerWidth, clientHeight: containerHeight } = chartContainer.value;
  myChart.value = echarts.init(chartContainer.value);

  try {
    const option = getAdaptiveOption(containerWidth, containerHeight);
    myChart.value.setOption(option);
    isLoading.value = false;

    const handleResize = () => {
      if (!myChart.value) return;
      const { clientWidth, clientHeight } = chartContainer.value;
      myChart.value.setOption(getAdaptiveOption(clientWidth, clientHeight));
      myChart.value.resize();
    };
    
    window.addEventListener('resize', handleResize);

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      myChart.value?.dispose();
    });

  } catch (error) {
    console.error('图表初始化失败：', error);
    isLoading.value = false;
    isError.value = true;
  }
};

onMounted(() => {
  nextTick(() => initChart());
});

onUnmounted(() => {
  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }
});
</script>

<style scoped>
.regression-analysis-chart {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  z-index: 1;
  overflow: hidden;
  border-radius: 8px;
}

.loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,10,30,0.3);
  border-radius: 8px;
  backdrop-filter: blur(4px);
  z-index: 2;
}

.loading-text {
  font-size: 16px;
  color: #00eaff;
  text-shadow: 0 0 10px rgba(0,255,255,0.5);
  letter-spacing: 2px;
  animation: flash 1.5s infinite alternate;
}

.error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(30,0,0,0.3);
  border-radius: 8px;
  backdrop-filter: blur(4px);
  z-index: 2;
}

.error-text {
  font-size: 16px;
  color: #ff4d4f;
  text-shadow: 0 0 10px rgba(255,0,0,0.5);
  letter-spacing: 2px;
}

@keyframes flash { from { opacity: 0.6; } to { opacity: 1; } }
</style>